﻿/***********************/
/* (c) Alexandru Lungu */
/*  Challenge is Life! */
/* www.challenge-me.ws */
/***********************/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IdentityModel.Policy;
using System.Security.Principal;
using System.IdentityModel.Claims;
using System.ServiceModel;

namespace Coowork.WcfServer
{
    //[3]
    public class ChallengeAuthorizationPolicy : IAuthorizationPolicy
    {
        Guid id = Guid.NewGuid();

        public bool Evaluate(EvaluationContext evaluationContext, ref object state)
        {
            IPrincipal user = OperationContext.Current.IncomingMessageProperties["Principal"] as IPrincipal;
            evaluationContext.Properties["Principal"] = user;
            evaluationContext.Properties["Identities"] = new List<IIdentity> { user.Identity };

            return false;
        }

        private IIdentity GetClientIdentity(EvaluationContext evaluationContext)
        {
            object obj;
            if (!evaluationContext.Properties.TryGetValue("Identities", out obj))
                throw new Exception("No Identity found!");

            IList<IIdentity> identities = obj as IList<IIdentity>;
            if (identities == null || identities.Count <= 0)
                throw new Exception("No Identity found!");

            return identities[0];
        }

        public System.IdentityModel.Claims.ClaimSet Issuer
        {
            get { return ClaimSet.System; }
        }

        public string Id
        {
            get { return id.ToString(); }
        }
    }

 
}